import 'package:flutter_web_server/ImcludeServer.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';

class ServerFileHelp {
  // 复制文件到沙盒，因为assets目录不能直接访问
  static Future<String?> copyFileFromAssets({
    bool isLaunchRemoveCache = true,
  }) async {
    String webfile = "webfile";
    String document = await FFPath.getPhoneLocalPath();
    String targetPath = "$document${Platform.pathSeparator}${webfile}";

    await FFDirectory.createDirectory(targetPath);
    log_info("targetPath = $document");

    String webPath = "$document${Platform.pathSeparator}${webfile}";
    bool indexExist = await FFDirectory.isExistDirectory(webPath);

    if (indexExist) {
      if (!isLaunchRemoveCache) {
        return webPath;
      }

      // 删除缓存
      await FFDirectory.deleteDirectory(webPath, recursive: true);
    }

    File webFile = await FFAssetFile.fileByAssets("assets/web.zip");
    bool success = await FFArchive.zipToFile2(zipPath: webFile.path, destinationDir: targetPath);
    log_info("解压状态 $success");
    return "$document${Platform.pathSeparator}${webfile}/web";
  }

  // 创建MIME类型解析器
  static MimeTypeResolver createMimeTypeParser() {
    // 创建MIME类型解析器
    final mimeTypes = <String, String>{
      '.html': 'text/html',
      '.css': 'text/css',
      '.js': 'application/javascript',
      '.json': 'application/json',
      '.png': 'image/png',
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.gif': 'image/gif',
      '.svg': 'image/svg+xml',
      '.ico': 'image/x-icon',
      '.woff': 'font/woff',
      '.woff2': 'font/woff2',
    };
    var mimeTypeResolver = MimeTypeResolver();
    mimeTypes.forEach((key, value) {
      mimeTypeResolver.addExtension(key, value);
    });

    return mimeTypeResolver;
  }

  // 创建静态文件处理器
  static Map<String, String> createStaticWeb({
    required String indexPath,
    required Router router,
  }) {
    // 创建MIME类型解析器
    var mimeTypeResolver = ServerFileHelp.createMimeTypeParser();

    // 指定静态文件目录
    var staticHandler = createStaticHandler(
      indexPath,
      defaultDocument: "index.html",
      serveFilesOutsidePath: true,
      contentTypeResolver: mimeTypeResolver,
    );

    // 将静态文件处理器添加到 Router 的根路径
    router.all('/<ignored|.*>', staticHandler);

    // 解决跨哉
    var overrideHeaders = {
      ACCESS_CONTROL_ALLOW_ORIGIN: '*', // Allow all origins
      ACCESS_CONTROL_ALLOW_METHODS: 'GET, POST, PUT, DELETE, OPTIONS', // Allow methods
      ACCESS_CONTROL_ALLOW_HEADERS: 'Origin, Content-Type, X-Auth-Token', // Allow headers
    };

    return overrideHeaders;
  }
}
